package com.tinem.platform.service.network.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.tinem.platform.module.pojo.vo.translate.TranslateReq;
import com.tinem.platform.module.pojo.vo.translate.TranslateRes;
import com.tinem.platform.service.network.service.TranslateService;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @program: platform
 * @description: ${description}
 * @author: eden#can
 * @Slogan: 没有所谓失败，除非你不再尝试
 * @date: 2021-11-10 16:41
 **/
@Slf4j
@Api(value = "trans")
@RestController
@RequestMapping("/trans")
public class TranslateApi {

    @Resource
    TranslateService translateService;


    @GlobalTransactional
    @PostMapping("/translate.api")
    @ApiOperation(value = "获取翻译结果", httpMethod = "POST", notes = "暂无")
    @ResponseBody
    public TranslateRes info(@RequestBody TranslateReq req) {
        log.info("translate.api req:{}",JSONUtil.toJsonStr(req));
        TranslateRes translateRes ;
//        TranslateRes translateRes = new TranslateRes();
        // 若源语言 & 目标语言一样，则直接将带翻译的结果
//        if(StrUtil.equals(req.getMsgLan(),req.getTarLan())){
//            BeanUtil.copyProperties(req,translateRes);
//            translateRes.setTarMsg(req.getMsg());
//            return translateRes;
//        }

        String shaStr = StrUtil.format("{}{}{}", req.getMsg(), req.getMsgLan(), req.getTarLan());
        String sha256 = SecureUtil.sha256(shaStr);
        //如果启用缓存，则从数据缓存中获取。
        if("enable".equals(req.getCache())){
            translateRes = translateService.getTranslateResult(req,sha256);
            if(translateRes != null){
                return translateRes;
            }
        }

        //如果无法从本地数据库文件中获取翻译信息，则使用第三方api。
        switch (req.getType()){
            case "baidu":
                translateRes  = translateService.getTranslateByBaiduResult(req);
                break;
            default:
                log.error("translate type（{}） is error",req.getType());
                return null;
            }
        if(translateRes!=null && StrUtil.isNotBlank(translateRes.getTarMsg())){
            //保存翻译信息到数据库
            try {
                translateService.saveTranslateResult(translateRes,sha256);
            }catch (Exception e){
                log.error("translate({}) save to db is error", JSONUtil.toJsonStr(translateRes));
            }
        }
        return translateRes;
    }

}
